import axios from 'axios'
import {ElMessage} from 'element-plus'
import {getToken} from "./auth";

const service = axios.create({
    baseURL: process.env.VUE_APP_BASEURL
});

service.interceptors.request.use(config => {
    // 判断是否有token
    config.headers['AUTH_TOKEN'] =  getToken();
    return config
}, (error) => {
    console.log(error)
});

service.interceptors.response.use(
    response => {
        const res = response.data;
        // 导出excel直接返回
        if (response.request.responseType === 'blob') {
            return res
        }
        if (res.code !== 0) {
            // 参数错误
            if (res.code === 50001) {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
            // 业务错误
            if (res.code === 50002) {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
            //认证错误
            if (res.code === 50003){
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
                window.location.href = '/login'
            }
            return Promise.reject()
        }else {
            return  res
        }
    },
    error => {
        ElMessage({
            message: '请求异常',
            type: 'error',
        })
        return Promise.reject(error)
    }
);
export default service